import sys
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSignal

from pts.task_engine import TaskEngine
import pts.global_variable as glv
from .Ui_mainwindow import Ui_MainWindow
from .sys_config import SysConfig
from .download_config import DownloadConfig
from .chan_config import ChanConfig
from .mess_browse import MessBrowse

from .real_time import RealTime
from .market_fund import MarketFund
from .ak_stocklist import AkStockList
from .hy_fundflow import HyFundFlow
from .gn_fundflow import GnFundFlow
from .bxzj_main import BxzjMain
from ..setting import SETTINGS, SETTING_FILENAME
from ..utility import save_json


class MainWindow(QMainWindow, Ui_MainWindow):
    """主窗口"""
    # 用于更新状态栏信息的信号
    sigStatusMess = pyqtSignal(str)

    # 行业、概念板块的固定项和排除项的存储文件
    file_GNblockGD = r'Data\GNblockGD.txt'
    file_GNblockPC = r'Data\GNblockPC.txt'
    file_HYblockGD = r'Data\HYblockGD.txt'
    file_HYblockPC = r'Data\HYblockPC.txt'

    def __init__(self, task_engine: TaskEngine):
        super(MainWindow, self).__init__()
        self.setupUi(self)

        # 从主程序接受到的任务引擎
        self.task_engine: TaskEngine = task_engine

        # ”北向资金“页面。这里先赋值为None，是避免用户不创建该页面时程序出错。别的页面不需要
        self.bxzj_main = None

        # 为信号关联槽函数
        self.sigStatusMess.connect(self.displayStatusMess)
        # 初始化行业、概念板块的固定项和排除项
        self.initBlocGDPC()
        # 初始化界面
        self.initUi()

        # 在状态栏显示信息
        self.displayStatusMess('本系统是《Python量化交易从入门到实战》一书(张少娴 等著)的作业系统。')

        # 启动任务引擎
        # 注：任务引擎要在界面初始化之后启动，因为任务在初始化界面的过程中创建
        self.task_engine.start()

    def displayStatusMess(self, mess):
        """在状态栏显示信息"""
        self.statusBar().showMessage(mess)

    def initBlocGDPC(self):
        """初始化行业、概念板块的固定项和排除项"""
        try:
            with open(self.file_GNblockGD, 'r', encoding='utf-8') as f:
                read_data = f.read()
                if read_data:
                    glv.gGNBlockGD.extend(read_data.split(','))
        except:
            pass

        try:
            with open(self.file_GNblockPC, 'r', encoding='utf-8') as f:
                read_data = f.read()
                if read_data:
                    glv.gGNBlockPC.extend(read_data.split(','))
        except:
            pass

        try:
            with open(self.file_HYblockGD, 'r', encoding='utf-8') as f:
                read_data = f.read()
                if read_data:
                    glv.gHYBlockGD.extend(read_data.split(','))
        except:
            pass

        try:
            with open(self.file_HYblockPC, 'r', encoding='utf-8') as f:
                read_data = f.read()
                if read_data:
                    glv.gHYBlockPC.extend(read_data.split(','))
        except:
            pass


    def initUi(self):
        """初始化界面"""

        # 设置窗口的图标
        self.setWindowIcon(QIcon(r'images\YuLan.png'))

        # 创建主QTableWidget
        self.tabWidget = QtWidgets.QTabWidget()
        self.tabWidget.setObjectName("tabWidget")

        # 以下创建各个页面
        # 注：如果有些页面不需要，将相关语句注释掉即可
        # 1-实时资金流
        self.real_time = RealTime(self.task_engine, self.sigStatusMess.emit)
        self.tabWidget.addTab(self.real_time, '实时资金流')

        # 2-大盘资金流
        self.market_fund = MarketFund(self.task_engine, self.sigStatusMess.emit)
        self.tabWidget.addTab(self.market_fund, '大盘资金流')

        # 3-个股资金流
        self.ak_stocklist = AkStockList(self, self.task_engine, self.sigStatusMess.emit)
        self.tabWidget.addTab(self.ak_stocklist, '个股资金流')

        # 4-行业板块资金流
        self.hy_fundflow = HyFundFlow(self.task_engine, self.sigStatusMess.emit)
        self.tabWidget.addTab(self.hy_fundflow, '行业板块资金流')

        # 5-概论板块资金流
        self.gn_fundflow = GnFundFlow(self.task_engine, self.sigStatusMess.emit)
        self.tabWidget.addTab(self.gn_fundflow, '概念板块资金流')

        # 6-北向资金
        self.bxzj_main = BxzjMain(self.task_engine, self.sigStatusMess.emit)
        self.tabWidget.addTab(self.bxzj_main, '北向资金')

        # 将主QTableWidget加入到主窗口的布局中
        # 注：self.hbox_main在QtDesigner中创建
        self.hbox_main.addWidget(self.tabWidget)
        self.tabWidget.setCurrentIndex(SETTINGS["CurrentIndex1"])

        # 关联“退出”菜单项的槽函数
        self.actExit.triggered.connect(self.close)

    @pyqtSlot()
    def on_actSysConfig_triggered(self):
        """系统配置"""
        w = SysConfig()
        w.initListBlocGDPC()
        w.exec_()

    @pyqtSlot()
    def on_actDownloadConfig_triggered(self):
        """行情数据源配置"""
        w = DownloadConfig()
        w.exec_()

    @pyqtSlot()
    def on_actChanConfig_triggered(self):
        """缠论配置"""
        w = ChanConfig()
        w.exec_()

    @pyqtSlot()
    def on_actMessBrowse_triggered(self):
        """消息查看"""
        w = MessBrowse(self.task_engine)
        w.exec_()

    @pyqtSlot()
    def on_actAbout_triggered(self):
        """关于"""
        QMessageBox.about(self, "关于 普吸金",
            """<b>普吸金交易辅助系统<br>(Ver 0.0.1)</b><br><br>
            本系统关注资金流向，充分利用网上公共资源，辅助对股票交易进行决策。目的是为广大散户朋友服务。<br><br>
            本系统是普吸金系列软件之一，是普吸金二次开发工具的具体应用，是《Python量化交易从入门到实战》（张少娴等著，清华大学出版社）一书的作业系统。<br>
            与本系统相关的所有资料和工具都可到QQ群881645236中下载。
            """
        )

    def closeEvent(self, event):
        """
        窗口关闭事件
        在退出程序时进行一些处理
        """
        '''reply = QMessageBox.question(self, '提示信息',
                                     '确认要关闭窗口？', QMessageBox.Yes |
                                     QMessageBox.No, QMessageBox.No)'''

        reply = QMessageBox.Yes
        if reply == QMessageBox.Yes:
            # 停止任务引擎
            self.task_engine.stop()

            # 保存配置项
            SETTINGS["CurrentIndex1"] = self.tabWidget.currentIndex()
            if self.bxzj_main:
                SETTINGS["CurrentIndex2"] = self.bxzj_main.tabWidget.currentIndex()
            save_json(SETTING_FILENAME, SETTINGS)

            event.accept()
        else:
            event.ignore()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ui = MainWindow()
    ui.showMaximized()
    sys.exit(app.exec_())
